package es.qb.deportivos.il.domain;

import java.io.Serializable;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

import javax.persistence.MappedSuperclass;
import javax.persistence.PrePersist;
import javax.persistence.PreUpdate;

import es.qb.deportivos.exception.GeneralBusinessException;
import es.qb.deportivos.util.Utilities;

@MappedSuperclass
public class GeneralDomainObject implements Serializable {

	/**
	 * 
	 */
	private static final long serialVersionUID = -7983456614157691292L;

	@PreUpdate
	@PrePersist
	public void cambiarVaciosNulosEnManyToOne() throws GeneralBusinessException {
		try {
			Field[] atributos = this.getClass().getDeclaredFields();
			for (int i = 0; i < atributos.length; i++) {
				Field atributo = atributos[i];
				if (atributo.getType().getName().contains("com.unav.becas.il.domain")) {
					Method metodo = this.getClass().getMethod("get" + Utilities.textoMayuscula(atributo.getName()), new Class[] {});
					Object o = metodo.invoke(this, new Object[] {});
					if (o != null) {
						metodo = o.getClass().getMethod("getId", new Class[] {});
						Integer id = (Integer) metodo.invoke(o, new Object[] {});
						if (id < 0) {
							metodo = this.getClass().getMethod("set" + Utilities.textoMayuscula(atributo.getName()),
									new Class[] { atributo.getType() });
							metodo.invoke(this, new Object[] { null });
						}
					}
				}
			}
		} catch (IllegalArgumentException e) {
			throw new GeneralBusinessException("Duplicar Objeto", "Error al duplica los datos del objeto");
		} catch (IllegalAccessException e) {
			throw new GeneralBusinessException("Duplicar Objeto", "Error al duplica los datos del objeto");
		} catch (InvocationTargetException e) {
			throw new GeneralBusinessException("Duplicar Objeto", "Error al duplica los datos del objeto");
		} catch (SecurityException e) {
			throw new GeneralBusinessException("Duplicar Objeto", "Error al duplica los datos del objeto");
		} catch (NoSuchMethodException e) {
			throw new GeneralBusinessException("Duplicar Objeto", "Error al duplica los datos del objeto");
		}
	}

}
